<template>
  <view class="user_info_container">
    <view class="form">
      <u-cell-group>
        <u-cell title="头像">
          <view class="avatar" slot="value" @click="uploadAvatar">
            <image class="avatar-pic" :src="avatar" mode="widthFix" />
          </view>
        </u-cell>
        <u-cell title="手机号">
          <view class="uni-value" slot="value">
            <uni-easyinput disabled v-model="mobile" placeholder="请输入手机号"></uni-easyinput>
          </view>
        </u-cell>
        <u-cell title="昵称">
          <view class="uni-value" slot="value">
            <uni-easyinput trim :clearable="false" v-model="nickname" placeholder="请输入昵称"></uni-easyinput>
          </view>
        </u-cell>
        <u-cell title="邮箱">
          <view class="uni-value" slot="value">
            <uni-easyinput trim :clearable="false" v-model="email" placeholder="请输入邮箱"></uni-easyinput>
          </view>
        </u-cell>
        <u-cell title="性别" is-link @click="showSexSelect = true">
          <view class="value" slot="value">
            {{ gender }}
            <u-action-sheet :actions="list" title="性别" :show="showSexSelect" @select="handleSelect" @close="showSexSelect = false"></u-action-sheet>
          </view>
        </u-cell>
        <u-cell title="出生日期" is-link @click="showDateSelect = true">
          <view class="value" slot="value">
            {{ birthdayFormat }}
            <u-datetime-picker :show="showDateSelect" :minDate="minDate" :maxDate="maxDate" confirmColor="#1A5276" v-model="birthday" @confirm="showDateSelect = false" @cancel="showDateSelect = false" mode="date"></u-datetime-picker>
          </view>
        </u-cell>
      </u-cell-group>
    </view>

    <view class="submit" @click="uploadUserInfo">
      <u-button text="保存"></u-button>
    </view>
    <Transition name="toast">
      <Toast v-if="globalLoading"></Toast>
    </Transition>
  </view>
</template>

<script lang="ts">
import Vue from 'vue'
import { dateFormatToString } from '@/utils/date'
import { UserTypes } from '@/store/actions_types/actions_types'
import { uploadAvatar, uploadUserInfo } from '@/api'
import { UserInfo } from '@/typings'
import { mapState } from 'vuex'

export default Vue.extend({
  data() {
    return {
      nickname: '',
      avatar: '',
      gender: '',
      email: '',
      mobile: '',
      birthday: 0,
      showSexSelect: false,
      showDateSelect: false,
      maxDate: new Date().getTime(),
      minDate: new Date('1970-01-01').getTime(),
      list: [
        {
          name: '男'
        },
        {
          name: '女'
        }
      ]
    }
  },
  computed: {
    ...mapState('user', ['globalLoading']),
    birthdayFormat() {
      return dateFormatToString(this.birthday)
    }
  },
  created() {
    const store = this.$store.state.user.userInfo as UserInfo
    if (!store.mobile) {
      uni.navigateTo({
        url: '/pages/login/login',
        success: () => {
          this.$store.commit(`user/${UserTypes.SET_REDIRECT}`, '/pages/uploadUserInfo/uploadUserInfo')
        }
      })
    } else {
      this.setUserInfo(store)
    }
  },
  methods: {
    // 性别选择
    handleSelect(value: { name: string }) {
      this.gender = value.name
    },
    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.birthday = userInfo.birthday ? Number(new Date(userInfo.birthday)) : Number(new Date('1970-01-01'))
      this.gender = userInfo.sex === 'male' ? '男' : '女'
      this.email = userInfo.email || ''
      this.mobile = userInfo.mobile || ''
      this.nickname = userInfo.nickname || ''
      this.avatar = userInfo.avatar || require('@/static/avatar/5810ea612ebb2_610.jpg')
    },
    // 上传用户头像
    uploadAvatar() {
      uni.chooseImage({
        count: 1,
        success: (res) => {
          const filePath = res.tempFilePaths[0]
          uni.getFileSystemManager().readFile({
            filePath: filePath, // 图片路径
            encoding: 'base64',
            success: async (data) => {
              const base64Data = 'data:image/png;base64,' + data.data
              // 显示加载动画
              this.$store.commit(`user/${UserTypes.SET_LOADING}`, true)
              // 上传用户头像
              try {
                const data = await uploadAvatar({
                  avatar: base64Data
                })
                if (data.code === 0) {
                  const userInfo = data.data as UserInfo
                  const payload = {
                    username: userInfo.username,
                    update_date: userInfo.update_date,
                    sex: userInfo.sex,
                    nickname: userInfo.nickname,
                    mobile: userInfo.mobile,
                    id: userInfo.id,
                    email: userInfo.email,
                    create_date: userInfo.create_date,
                    birthday: userInfo.birthday,
                    avatar: userInfo.avatar
                  }
                  this.avatar = process.env.VUE_APP_BASE_DEV + userInfo.avatar
                  // 更新用户信息
                  this.$store.commit(`user/${UserTypes.SET_USER_INFO}`, payload)
                  this.setErrorTip('头像上传成功', 'success')
                } else {
                  this.setErrorTip(data.message)
                }
              } catch (err) {
                console.log(err)

                this.setErrorTip('头像上传失败')
              }
            },
            fail: () => {
              this.setErrorTip('文件读取失败')
            }
          })
        },
        fail: () => {
          this.setErrorTip('文件选择失败')
        }
      })
    },
    // 上传用户信息
    async uploadUserInfo() {
      const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
      if (!this.mobile) {
        return this.setErrorTip('手机号必填<br>请先登录')
      }
      if (!/^1[3-9]\d{9}$/.test(this.mobile)) {
        return this.setErrorTip('手机号格式错误')
      }
      // 昵称必填
      if (!this.nickname) {
        return this.setErrorTip('请输入昵称')
      }
      if (this.nickname.length > 32) {
        return this.setErrorTip('昵称最大长度为32位')
      }
      // 邮箱必填
      if (!this.email) {
        return this.setErrorTip('请输入邮箱')
      }
      if (!emailRegex.test(this.email)) {
        return this.setErrorTip('邮箱格式不正确')
      }
      // 创建上传信息
      const payload = {
        mobil: this.mobile,
        nickname: this.nickname,
        email: this.email,
        sex: this.gender === '男' ? 'male' : 'female',
        birthday: this.birthdayFormat
      }
      // 上传用户信息
      try {
        this.$store.commit(`user/${UserTypes.SET_LOADING}`, true)
        const data = await uploadUserInfo(payload)
        if (data.code === 0) {
          this.setErrorTip('上传成功', 'success')
        } else {
          this.setErrorTip(data.message)
        }
      } catch (err) {
        this.setErrorTip('上传失败<br>请检查网络')
      }
    },
    // 设置加载信息
    setErrorTip(message: string, loading_type: 'waring' | 'loading' | 'success' = 'waring') {
      this.$store.commit(`user/${UserTypes.SET_LOADING_TYPE}`, loading_type)
      this.$store.commit(`user/${UserTypes.SET_MESSAGE}`, message)
      this.$store.commit(`user/${UserTypes.SET_LOADING}`, true)
    }
  }
})
</script>

<style lang="scss" scoped>
.user_info_container {
  font-family: 'aliregular';
  height: 100vh;
  background-color: $uni-bg-color-grey;

  .form {
    background-color: #fff;

    .avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 999rpx;
      overflow: hidden;

      .avatar-pic {
        width: 100%;
      }
    }

    .value {
      color: $uni-theme-light-color;
      font-size: 24rpx;
      text-align: right;
      flex: 1;
    }

    .uni-value {
      flex: 1;
    }

    ::v-deep .u-cell__body {
      justify-content: space-between;

      .u-cell__body__content {
        flex: none !important;
      }

      .u-cell__title-text {
        white-space: nowrap;
      }
      .is-input-border {
        border: none;
        border-radius: 0;
      }
      .uni-easyinput__content-input {
        height: auto;
        text-align: right;
        padding-left: 0 !important;
        color: $uni-theme-light-color;
        font-size: 24rpx;
      }

      .is-disabled {
        background-color: #fff !important;
      }
    }
  }

  .submit {
    margin-top: 200rpx;
    padding: 0 10rpx;

    ::v-deep .u-button--info {
      background-color: $uni-primary !important;
      color: #fff !important;
    }
  }
}
</style>
